package deepr.core;

import deepr.exception.DeeprAssert;
import deepr.exception.DeeprException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.ClassArrayEditor;
import org.springframework.util.Assert;
import sun.util.resources.cldr.zu.CalendarData_zu_ZA;

import java.util.Arrays;
import java.util.HashMap;

@Slf4j
public class SchemaManager {

  protected static HashMap<Class<?>, SchemaData> schemaStore = new HashMap<>();

  protected static HashMap<String, Class<?>> objectStore = new HashMap<>();

  public static void print() {
    objectStore.forEach((key, v) -> {
      log.info("object: {}, schemaData: {}", key, schemaStore.get(v));
    });
  }

  public static void putObject(String object, Class<?> schema) {
    objectStore.put(object, schema);
  }

  public static void putSchema(Class<?> czz, SchemaData schemaData) {
    schemaStore.put(czz, schemaData);
  }

  public static void removeObject(String object) {
    objectStore.remove(object);
  }

  public static void removeObject(String[] objects) {
    Arrays.stream(objects).forEach(object -> {
      objectStore.remove(object);
    });
  }

  public static SchemaData getSchemaData(String object) {
    Class<?> czz = objectStore.get(object);
    Assert.isTrue(czz != null, object + " not exists");
    SchemaData schemaData = schemaStore.get(czz);
    Assert.isTrue(schemaData != null, czz + " not exists");
    return schemaData;
  }

  public static SchemaData getSchemaData(Class<?> czz) {
    SchemaData schemaData = schemaStore.get(czz);
    Assert.isTrue(schemaData != null, czz + " not exists");
    return schemaData;
  }

  public static SchemaData getForeignSchemaData(SchemaData schemaData, String property) throws DeeprException {
    PropertyData propertyData = schemaData.getPropertyData(property);
    DeeprAssert.isTrue(propertyData != null, schemaData.getName() + " for " + property + " not exists");
    DeeprAssert.isTrue(propertyData.isSchema(), schemaData.getName() + " for " + property + " not not is schema");
    return SchemaManager.getSchemaData(propertyData.getSchema());
  }

}
